<template>
  <div >
    <el-upload
      :action="`${path}/fileUploadAndDownload/upload`"
      :before-upload="checkFile"
      :on-error="uploadError"
      :headers="{ 'x-token': userStore.token }"
      :on-success="uploadSuccess"
      :show-file-list="false"
      class="upload-btn"
    
    >
      <el-button type="primary">普通上传</el-button>
    </el-upload>
  </div>
  <div class="zhezhao" v-loading="fullscreenLoading" v-if="fullscreenLoading">
    <div v-loading="fullscreenLoading"></div>
  </div>
</template>

<script setup>

import { ref } from 'vue'
import { ElMessage,ElLoading } from 'element-plus'
import { isVideoMime, isImageMime } from '@/utils/image'
import { useUserStore } from '@/pinia/modules/user'


defineOptions({
  name: 'UploadCommon',
})

const userStore = useUserStore()

const emit = defineEmits(['on-success'])
const path = ref(import.meta.env.VITE_BASE_API)

const fullscreenLoading = ref(false)

const checkFile = (file) => {
  fullscreenLoading.value = true
  
  // const isLt500K = file.size / 1024 / 1024 < 0.5 // 500K, @todo 应支持在项目中设置
  const isLt500K = file.size / 1024 / 1024 < 10 //普通上传限制大小
  const isLt5M = file.size / 1024 / 1024 < 1000 // 5MB, @todo 应支持项目中设置  压缩上传限制大小
  const isVideo = isVideoMime(file.type)
  const isImage = isImageMime(file.type)
  let pass = true
  if (!isVideo && !isImage) {
    ElMessage.error('上传图片只能是 jpg,png,svg,webp 格式, 上传视频只能是 mp4,webm 格式!')
    fullscreenLoading.value = false
    pass = false
  }
  if (!isLt5M && isVideo) {
    ElMessage.error('上传视频大小不能超过 100MB')
    fullscreenLoading.value = false
    pass = false
  }
  if (!isLt500K && isImage) {
    ElMessage.error('未压缩的上传图片大小不能超过 10MB，请使用压缩上传')
    fullscreenLoading.value = false
    pass = false
  }

  console.log('upload file check result: ', pass)

  return pass
}

const uploadSuccess = (res) => {
  const { data } = res
  if (data.file) {
    emit('on-success', data.file.url)
    fullscreenLoading.value = false
  }
}

const uploadError = () => {
  ElMessage({
    type: 'error',
    message: '上传失败'
  })
  fullscreenLoading.value = false
}

</script>

<style scoped>
.zhezhao{
  width: 100%;
  height: 300vh;
  position: absolute;
  z-index: 999;
 
}
</style>